#!/usr/bin/python3

import json, sys
import lark_oapi as lark
from lark_oapi.api.im.v1 import *
import requests


# 1、飞书严重报警通知
def old(text):
    headers = {"Content-Type": "application/json;charset=utf-8"}
    url = "https://open.feishu.cn/open-apis/bot/hook/0f868b8c977749cca07329d3b30cf37a"
    response = requests.post(url, text, headers=headers)
    print(response)


# 2、飞书加急消息测试
# 功能：发送加急消息和加急电话
def main(text):
    # 创建client
    open_id = "ou_432a39ff89c0a65e5ebe81406f0e3f96"  # 飞书openid：叶修

    client = (
        lark.Client.builder()
        .app_id("cli_a73575b6fdfd500e")
        .app_secret("E3uOcg61jnYJaX4NCUIeHWnk5Hr0Jljf")
        .log_level(lark.LogLevel.DEBUG)
        .build()
    )

    # 发送加急消息
    request: CreateMessageRequest = (
        CreateMessageRequest.builder()
        .receive_id_type("open_id")
        .request_body(
            CreateMessageRequestBody.builder()
            .receive_id(open_id)
            .msg_type("text")
            .content(text)
            .build()
        )
        .build()
    )

    # 发起请求
    response: CreateMessageResponse = client.im.v1.message.create(request)

    # 处理失败返回
    if not response.success():
        lark.logger.error(
            f"client.im.v1.message.create failed, code: {response.code}, msg: {response.msg}, log_id: {response.get_log_id()}, resp: \n{json.dumps(json.loads(response.raw.content), indent=4, ensure_ascii=False)}"
        )
        return

    # 处理业务结果
    lark.logger.info(lark.JSON.marshal(response.data, indent=4))

    # 发送语音：
    request: UrgentPhoneMessageRequest = (
        UrgentPhoneMessageRequest.builder()
        .message_id(response.data.message_id)
        .user_id_type("open_id")
        .request_body(UrgentReceivers.builder().user_id_list([open_id]).build())
        .build()
    )

    # 发起请求
    response: UrgentPhoneMessageResponse = client.im.v1.message.urgent_phone(request)

    # 处理失败返回
    if not response.success():
        lark.logger.error(
            f"client.im.v1.message.urgent_phone failed, code: {response.code}, msg: {response.msg}, log_id: {response.get_log_id()}, resp: \n{json.dumps(json.loads(response.raw.content), indent=4, ensure_ascii=False)}"
        )
        return

    # 处理业务结果
    lark.logger.info(lark.JSON.marshal(response.data, indent=4))


if __name__ == "__main__":
    text = json.dumps({"title": "严重级别报警通知", "text": sys.argv[1]})

    old(text)
    main(text)